<!--JMES通用流水报工-->
<template>
  <div class="app-container">
    <!--    报工区域-->
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="opetatarea">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="固定工艺">
                  <el-input v-model="lockProcessName" placeholder="请选择固定工艺" disabled >
                    <el-button slot="append" icon="el-icon-search" @click="openSelectProcess= true"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="生产工单" prop="moCode">
                  <el-input v-model="form.moCode" placeholder="请输入生产工单" :disabled="true">
                    <el-button slot="append" icon="el-icon-search" @click="openSelectSingleMo = true"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报工人" prop="userId">
                  <el-input :value="nickname" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="流水号" prop="serialNo">
                  <el-input v-model="form.serialNo" placeholder="请输入流水号">
                    <el-button slot="append" icon="el-icon-search" @click="getMoDetail"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报工工序" prop="moRouteId">
                  <el-select v-model="form.moRouteId" placeholder="请选择">
                    <div v-for="item in form.routes" >
                      <el-option :key="item.id" :label="item.processName" :value="item.id" @click.native="changeProcess(item)"></el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-table :data="form.entryList" v-loading="load">
                <el-table-column label="检验项目" align="center" prop="entryName" fixed="left" width="150px" />
                <el-table-column label="检验工具" align="center" prop="inspectTools" />
                <el-table-column label="检验方法" align="center" prop="inspectMethod" />
                <el-table-column label="检验标准" align="center" prop="standardStr" />
                <el-table-column label="标准值" align="center" prop="standard" />
                <el-table-column label="误差上限" align="center" prop="standardUp" />
                <el-table-column label="误差下限" align="center" prop="standardDown" />
                <el-table-column label="实际检验值" align="center" prop="reality" width="150px" fixed="right">
                  <template v-slot="scope">
                    <el-input type="number" v-model="scope.row.reality" :disabled="scope.row.standard == null || scope.row.standard == undefined" @input="changeReality(scope.row)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="检验结论" align="center" prop="inspectResult"  width="150px" fixed="right">
                  <template v-slot="scope">
                    <el-select v-model="scope.row.inspectResult" placeholder="请选择检测结果">
                      <el-option v-for="dict in inspectOptions"
                                 :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" style="margin-top: 20px">
            <el-button type="primary" @click="submitForm">报 工</el-button>
            <el-button @click="cancel">重 置</el-button>
          </div>
          <el-row v-show="form">
            <el-col :span="24">
              <el-divider content-position="left">生产信息</el-divider>
              <el-descriptions border>
                <el-descriptions-item label="工厂">{{ form.factoryName }}</el-descriptions-item>
                <el-descriptions-item label="生产车间">{{ form.workshopName }}</el-descriptions-item>
                <el-descriptions-item label="部门">{{ form.deptName }}</el-descriptions-item>
                <el-descriptions-item label="批次号">{{ form.batchNo }}</el-descriptions-item>
                <el-descriptions-item label="生产计划">{{ form.planCode }}</el-descriptions-item>
                <el-descriptions-item label="排产数量">{{ form.produceAmount }}</el-descriptions-item>
                <el-descriptions-item label="产品名称">{{ form.itemName }}</el-descriptions-item>
                <el-descriptions-item label="产品代码">{{ form.itemCode }}</el-descriptions-item>
                <el-descriptions-item label="产品图号">{{ form.drawCode }}</el-descriptions-item>
                <el-descriptions-item label="产品规格">{{ form.spec }}</el-descriptions-item>
                <el-descriptions-item label="工艺卡片">
                  <image-preview :src="activeProcess" :width="'50px'" :height="'50px'"></image-preview>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="opetatarea">
          <el-collapse value="1" :accordion="true">
            <el-collapse-item title="生产状态" name="1">
              <el-steps :active="activeStep" align-center finish-status="success">
                <el-step v-for="(item, index) in form.routes" :key="item.id" :title="item.processName">
                  <template slot="description">
                    <p>排产数量：{{form.produceAmount}}</p>
                    <p>报工数量：{{item.produceAmount}}</p>
                  </template>
                </el-step>
              </el-steps>
            </el-collapse-item>
            <el-collapse-item title="报工数据" name="2">
              <!-- 搜索工作栏 -->
              <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="生产工单" prop="moId" v-show="false">
                  <el-input v-model="queryParams.moId" placeholder="请输入生产排产ID" clearable @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="生产工单" prop="moCode">
                  <el-input v-model="queryParams.moCode" placeholder="请选择生产工单" disabled >
                    <el-button slot="append" icon="el-icon-search" @click="openSelectSingleMoQuery = true"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="产品信息" prop="itemProduceId" v-show="false">
                  <el-input v-model="queryParams.itemProduceId" placeholder="请选择产品信息" clearable @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="产品信息" prop="itemCode">
                  <el-input v-model="queryParams.itemCode" placeholder="请选择产品信息" disabled >
                    <el-button slot="append" icon="el-icon-search" @click="openSelectItemProduceQuery = true"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="流水号" prop="serialNo">
                  <el-input v-model="queryParams.serialNo" placeholder="请输入流水号" clearable @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 列表 -->
              <el-table v-loading="loading" :data="list" height="550">
                <el-table-column label="序号" align="center" prop="id" fixed="left" />
                <el-table-column label="生产工单" align="center" prop="moCode" fixed="left" width="180px" />
                <el-table-column label="工厂" align="center" prop="factoryName" show-overflow-tooltip />
                <el-table-column label="生产车间" align="center" prop="workshopName" show-overflow-tooltip />
                <el-table-column label="工作中心" align="center" prop="centerName" show-overflow-tooltip />
                <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip />
                <el-table-column label="批次号" align="center" prop="batchNo" width="150px" show-overflow-tooltip />
                <el-table-column label="生产计划" align="center" prop="planCode" width="150px" show-overflow-tooltip />
                <el-table-column label="流水号" align="center" prop="serialNo" width="150px" show-overflow-tooltip />
                <el-table-column label="报工工序" align="center" prop="processName" show-overflow-tooltip />
                <el-table-column label="报工数量" align="center" prop="reportAmount" show-overflow-tooltip />
                <el-table-column label="产品名称" align="center" prop="itemName" width="100px" show-overflow-tooltip />
                <el-table-column label="产品代码" align="center" prop="itemCode" width="100px" show-overflow-tooltip />
                <el-table-column label="产品规格" align="center" prop="spec" width="100px" show-overflow-tooltip />
                <el-table-column label="产品图号" align="center" prop="drawCode" width="100px" show-overflow-tooltip />
                <el-table-column label="报工人" align="center" prop="userName" show-overflow-tooltip />
                <el-table-column label="报工时间" align="center" prop="createTime" width="180" show-overflow-tooltip>
                  <template v-slot="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="80">
                  <template v-slot="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['mes:report:delete']">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页组件 -->
              <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                          @pagination="getList"/>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12"></el-col>
      <el-col :span="12"></el-col>
    </el-row>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" v-dialogDrag append-to-body>

    </el-dialog>

    <!-- 查询产品生产信息(查询使用) -->
    <selectItemProduce :openSelectItemProduce.sync='openSelectItemProduceQuery' @selectItemProduce='selectItemProduceQuery'></selectItemProduce>
    <!-- 查询产品生产计划 -->
    <selectSinglePlan :openSelectSinglePlan.sync="openSelectSinglePlan" @selectSinglePlan="selectSinglePlan"></selectSinglePlan>
    <!-- 查询产品生产工单(查询使用) -->
    <selectSingleMo :openSelectSingleMo.sync="openSelectSingleMoQuery" @selectSingleMo="selectSingleMoQuery"></selectSingleMo>
    <!-- 查询产品生产工单（报工使用） -->
    <selectSingleMo :openSelectSingleMo.sync="openSelectSingleMo" @selectSingleMo="selectSingleMo"></selectSingleMo>
    <!--  选择工艺  -->
    <SelectProcess :openSelectProcess="openSelectProcess" @selectProcess="selectProcess"></SelectProcess>
  </div>
</template>

<script>
import { createReport, updateReport, deleteReport, getReport, getReportPage, exportReportExcel } from "@/api/mes/report";
import { getMoDetail } from "@/api/mes/moDetail"
import { getInspectSchemeByItem } from '@/api/qms/inspectScheme'
import { getMoInfo } from "@/api/mes/mo"
import SelectFactory from '@/components/SelectFactory/index.vue'
import SelectCenter from '@/components/SelectCenter/index.vue'
import SelectDept from '@/components/SelectDept/index.vue'
import SelectSinglePlan from '@/components/SelectSinglePlan/index.vue'
import SelectItemProduce from '@/components/SelectItemProduce/index.vue'
import SelectSingleMo from '@/components/SelectSingleMo/index.vue'
import SelectMultipleUser from '@/components/SelectMultipleUser/index.vue'
import SelectWorkshop from '@/components/SelectWorkshop/index.vue'
import { mapGetters } from 'vuex'
import ImagePreview from '@/components/ImagePreview/index.vue'
import SelectProcess from '@/components/SelectProcess/index.vue'

export default {
  name: "Batch",
  components: {
    SelectFactory,
    SelectCenter,
    SelectDept,
    SelectSinglePlan,
    SelectItemProduce,
    SelectSingleMo,
    SelectMultipleUser,
    SelectWorkshop,
    ImagePreview,
    SelectProcess
  },
  computed: {
    ...mapGetters([
      'nickname',
    ]),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      load: false,
      // 当前工艺
      activeStep: undefined,
      // 固定工艺
      lockProcess: undefined,
      lockProcessName: undefined,
      // 当前工艺卡片
      activeProcess: undefined,
      // 选择产品弹窗
      openSelectItemProduceQuery: false,
      // 打开选择生产计划
      openSelectSinglePlan: false,
      // 打开选择生产工单
      openSelectSingleMoQuery: false,
      // 打开选择生产工单
      openSelectSingleMo: false,
      // 打开选择工艺
      openSelectProcess: false,
      // 报工数量输入框
      reportAmountInputDisable: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 检验结论选项
      inspectOptions: [],
      // 总条数
      total: 0,
      // 生产报工列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        moId: null,
        moCode: null,
        planId: null,
        planCode: null,
        batchNo: null,
        itemId: null,
        itemCode: null,
        itemProduceId: null,
        factoryId: null,
        workshopId: null,
        centerId: null,
        deptId: null,
        userId: null,
        cooperate: null,
        processId: null,
        serialNo: null,
        approveTime: [],
        approveUser: null,
        approve: null,
        createTime: [],
      },
      // 表单参数
      form: {},
      entryList: [],
      // 表单校验
      rules: {
        moId: [{ required: true, message: "生产排产ID不能为空", trigger: "blur" }],
        moCode: [{ required: true, message: "生产工单不能为空", trigger: "blur" }],
        moRouteId: [{ required: true, message: "报工工序不能为空", trigger: "blur" }],
        reportAmount: [{ required: true, message: "报工数量不能为空", trigger: "blur" }],
        serialNo: [{ required: true, message: "流水号不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.reset();
    this.getDict();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getReportPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /* 查询检验方案 */
    async getInspectScheme(itemId) {
      await getInspectSchemeByItem(itemId, 2).then(response => {
        this.entryList = [];
        if (response.data != null && response.data != undefined && response.data.entryList != null && response.data.entryList != undefined){
          this.entryList = response.data.entryList;
        }

      })
    },
    /* 获取字典 */
    getDict() {
      this.inspectOptions = this.getDictDatas(this.DICT_TYPE.QMS_INSPECT_RESULT)
    },
    /* 实际检验值改变事件 */
    changeReality(obj) {
      obj.inspectResult = 1;
      if (obj != null && obj != undefined && obj.reality != null && obj.reality != undefined && obj.standard !=null && obj.standard != undefined) {
        if (obj.standardUp != null && obj.standardUp != undefined && obj.reality > (obj.standard+obj.standardUp)){
          obj.inspectResult = 2;
        }
        if (obj.standardDown != null && obj.standardDown != undefined && obj.reality < (obj.standard-obj.standardDown)){
          obj.inspectResult = 2;
        }
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        moId: undefined,
        cooperate: undefined,
        moRouteId: undefined,
        reportAmount: 1,
        serialNo: undefined,
        reportType: 'serial',
      };
      this.resetForm("form");
    },
    /* 选择生产计划 */
    selectSinglePlan(data) {
      this.queryParams.planId = data.id;
      this.queryParams.planCode = data.code;
    },
    /* 选择工艺 */
    selectProcess(data) {
      this.lockProcess = data.id;
      this.lockProcessName = data.name;
      this.openSelectProcess = false;
    },
    /** 选择产品生产信息回调 */
    selectItemProduceQuery(item) {
      this.queryParams.itemProduceId = item.id;
      this.queryParams.itemCode = item.itemCode;
    },
    /* 选择产品生产工单 */
    selectSingleMoQuery(data) {
      this.queryParams.moId = data.id;
      this.queryParams.moCode = data.code;
    },
    /* 选择产品生产工单 */
    selectSingleMo(data) {
      this.form.moCode = data.code
      this.getMoFun(data.id)

    },
    /* 查询生产工单 */
    async getMoFun(id) {
      await getMoInfo(id).then(response => {
        const data = response.data;
        const moId = data.id;
        const moCode = data.code;
        this.form = data;
        this.form.moId = moId;
        this.form.moCode = moCode;
        this.form.moRouteId = undefined;
        this.activeStep = undefined;
        this.form.reportType = 'serial';
        this.form.reportAmount = 1;
        this.activeProcess = undefined;

      })
      // 获取检验方案
      await this.getInspectScheme(this.form.itemId);
      await this.getDefaultProcess();
    },
    /* 获取默认工艺 */
    getDefaultProcess(){
      if (this.lockProcess === null || this.lockProcess === undefined) {
        return;
      }
      if (this.form.routes=== null || this.form.routes === undefined || this.form.routes.length === 0) {
        return;
      }
      const route = this.form.routes.find((item) => {
        return item.processId === this.lockProcess
      })
      if (route === null || route === undefined){
        return;
      }
      this.form.moRouteId = route.id;
      this.changeProcess(route);
    },
    /* 通过流水号查询工单信息 */
    async getMoDetail() {
      await getMoDetail(this.form.serialNo).then(response => {
        if (response.data === null || response.data === undefined) {
          this.$modal.msg('未查询到生产工单信息');
          return;
        }
        let serialNo = this.form.serialNo;
        const data = response.data;
        this.getMoFun(data.moId).then(response =>  {
          this.$set(this.form, 'serialNo', serialNo)
        })
      })
    },
    /* 选择工序事件 */
    changeProcess(row) {
      const routes = this.form.routes.filter(process => {
        return row.id === process.id;
      })
      this.activeStep = routes[0].subsequence-1;
      this.activeProcess = routes[0].processFile;
      // 处理质量数据
      this.load = true;
      this.form.entryList = this.entryList.filter(item => {
        return item.processId == row.processId;
      })
      this.load = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产报工";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getReport(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产报工";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 添加的提交
        createReport(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.reset();
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除生产报工编号为"' + id + '"的数据项?').then(function() {
          return deleteReport(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有生产报工数据项?').then(() => {
          this.exportLoading = true;
          return exportReportExcel(params);
        }).then(response => {
          this.$download.excel(response, '生产报工.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
.app-container {
  .opetatarea {
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    height: 850px;
  }
}
</style>
